package com.studentManagement.servlet;

import com.studentManagement.daoImpl.*;
import com.studentManagement.po.*;
import com.studentManagement.po.Class;
import com.studentManagement.service.ClassService;
import com.studentManagement.serviceImpl.ClassServiceImpl;
import com.studentManagement.utils.Bean_MapUtil;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/1 0001.
 */
@WebServlet(name = "ClassServlet")
public class ClassServlet extends HttpServlet {
    
    ClassService classService = new ClassServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
//        System.out.println(action);
        if (action.equals("getStudentData")) {
            getStudentData(request,response);//获取某页学生列表(url)
        }else if(action.equals("addClass")){
            addClass(request, response);//添加班级
        }else if(action.equals("varityClass_id")){
            varityClass_id(request,response);//验证class_id是否可用
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        if (action.equals("getStudentLeader")) {
            getStudentLeader(request,response);//得到班干列表(class_id)
        } else if(action.equals("getClassList")){
            getClassList(request, response);//得到所有班级列表
        }else if (action.equals("getPageSum")) {
            getPageSum(request,response);//得到分页页数（url)
        }else if (action.equals("getSchedule")) {
            getSchedule(request, response);//得到课程表(使用freemark生成html)
        }else if(action.equals("getAllDepartmentInfo")){
            getAllDepartmentInfo(request, response);//预读数据库的部门信息，添加下拉框内容
        }else if(action.equals("getAllTeacherInfo")){
            getAllTeacherInfo(request, response);//预读数据库的辅导员信息，添加下拉框内容
        }
    }
    /**
     * 方法的功能描述：得到所有班级列表
     * @params：[request, response]
     * @return: void */
    private void getClassList(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        List<String> list=classService.getClassList();
        out.print("<message>");
        for (int i = 0; i <list.size() ; i++) {
            out.print("<class_id>"+list.get(i).toString()+"</class_id>");
        }
        out.print("</message>");
    }
    /**
     * 方法的功能描述：验证class_id是否可用
     * @params：[request, response]
     * @return: void */
    private void varityClass_id(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
        String class_id=request.getParameter("class_id");
        PrintWriter out=response.getWriter();
        List<String> class_ids=new ClassDaoImpl().queryAllClass_id();
        boolean boo=true;
        for (int i = 0; i <class_ids.size() ; i++) {
            if(class_id.equals(class_ids.get(i).toString())){
                System.out.println("true");
                boo=false;
            }
        }
        out.print(boo);
    }

    /**
     * 方法的功能描述：添加班级
     * @params：[request, response]
     * @return: void */
    private void addClass(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //取值
        String class_id=request.getParameter("class_id");
        String class_name=request.getParameter("class_name");
        int class_department_id= Integer.parseInt(request.getParameter("class_department_id"));
        String class_teacher_id=request.getParameter("class_teacher_id");
        int class_enter_year= Integer.parseInt(request.getParameter("class_enter_year"));
        //赋值
        Class cl=new Class();
        cl.setClass_id(class_id);
        cl.setClass_name(class_name);
        cl.setClass_department_id(class_department_id);
        cl.setClass_teacher_id(class_teacher_id);
        cl.setClass_enter_year(class_enter_year);
        //插入班级
        String boo="添加成功";
        try {
            new ClassDaoImpl().addClass(cl);
        } catch (SQLException e) {
            boo="添加失败";
        }
        //返回前端
        PrintWriter out =response.getWriter();
        out.print(boo);
    }
    /**
     * 方法的功能描述：预读数据库的辅导员信息，添加下拉框内容
     * @params：[request, response]
     * @return: void */
    private void getAllTeacherInfo(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        JSONArray jsonArray= null;
        try {
            jsonArray = JSONArray.fromObject(new TeacherDaoImpl().queryAllTeacher());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        out.print(jsonArray);
    }

    /**
     * 方法的功能描述：预读数据库的部门信息，添加下拉框内容
     * @params：[request, response]
     * @return: void */
    private void getAllDepartmentInfo(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        JSONArray jsonArray = null;
        try {
            jsonArray =JSONArray.fromObject(new DeparmentDaoImpl().queryAllDepartment());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        out.print(jsonArray);
    }

    /**
     * 方法的功能描述：获取某页学生列表(url)
     * @params：[request, response]
     * @return: void */
    private void getStudentData(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {

        PrintWriter out=response.getWriter();
        int currentPage= Integer.parseInt(request.getParameter("currentPage"));
        String methods=request.getParameter("methods");
        if (methods.equals("studentList")){
            String class_id = (String) request.getSession().getAttribute("class_id");
            List<Student_simple> studentList = classService.forRightClassServlet_getStudentList(class_id, (currentPage - 1) * 10, 10);
            JSONArray jsonArray=JSONArray.fromObject(studentList);
            out.print(jsonArray);
        }else if(methods.equals("keywords")){
            String keywords=request.getParameter("keywords");
            List<Student> student= new StudentDaoImpl().getStudentDetail_byKeywords(keywords,currentPage,10);
            JSONArray jsonArray=JSONArray.fromObject(student);
            out.print(jsonArray);
        }

    }
    /**
     * 方法的功能描述：得到班干列表(class_id)
     * @params：[request, response]
     * @return: void */
    private void getStudentLeader(HttpServletRequest request,HttpServletResponse response)throws  ServletException,IOException{

        String class_id = (String) request.getSession().getAttribute("class_id");
        List<Student_Leader> list = classService.getStudent_leader(class_id);
        request.getSession().setAttribute("studentLeader", list);
        response.sendRedirect(request.getContextPath() + "/jsp/teacher/class/studentLeader.jsp");
    }
    /**
     * 方法的功能描述：得到分页页数（url)
     * @params：[request, response]
     * @return: void */
    private void getPageSum(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        String methods=request.getParameter("methods");
        int pageNum=0;
        if (methods.equals("studentList")){//学生一览，分页页数
            String class_id = (String) request.getSession().getAttribute("class_id");
            pageNum = new ClassServiceImpl().getPagingNum_class_id(class_id, 10);
        }else if(methods.equals("keywords")){//关键词查询后，分页页数
            String keywords=request.getParameter("keywords");
            pageNum=new ClassServiceImpl().getPagingNum_keywords(keywords,10);

        }
        out.print(pageNum);
    }
    /**
     * 方法的功能描述：得到课程表(使用freemark生成html)
     * @params：[request, response]
     * @return: void */
    private void getSchedule(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Configuration configuration = new Configuration(Configuration.VERSION_2_3_26);
        configuration.setDirectoryForTemplateLoading(new File(getServletContext().getRealPath("/resources/ftl")));
        configuration.setDefaultEncoding("utf-8");
        String class_id= (String) request.getSession().getAttribute("class_id");
        String grade=request.getParameter("grade");
        String term=request.getParameter("term");
        int class_id_year= Integer.parseInt(class_id.substring(1,3))+2000;
        //把grade转换成schedule_year
        String schedule_year="";
        if (grade.equals("1")) schedule_year=class_id_year+"-"+(class_id_year+1);
        else if(grade.equals("2")) schedule_year=class_id_year+1+"-"+(class_id_year+2);
        else if(grade.equals("3")) schedule_year=class_id_year+2+"-"+(class_id_year+3);
        else if(grade.equals("4")) schedule_year=class_id_year+3+"-"+(class_id_year+4);
        //把term转换成schedule_term
        String schedule_term="";
        if(term.equals("1")) schedule_term="一";
        else if(term.equals("2")) schedule_term="二";

        try {
            Schedule schedule = new ScheduleDaoImpl().queryAllSchedule(class_id, schedule_year, schedule_term);
            Map<String, Object> map = Bean_MapUtil.transform(schedule);
            Template template = configuration.getTemplate("scheduleTable.ftl");
            Writer out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(getServletContext().getRealPath("/jsp/teacher/class/scheduleTable.html")), "UTF-8"));
            template.process(map, out);
        } catch (TemplateException e) {
        }
        request.getRequestDispatcher(request.getContextPath()+"/jsp/teacher/class/scheduleTable.html?grade="+grade+"&term="+term+"target=_blank").forward(request,response);
    }


}
